package com.mes.loco.aps.server.controller.aps;

import com.iplant.aps.controller.BaseController;
import com.iplant.aps.service.APSService;
import com.iplant.aps.service.MyHelperService;
import com.iplant.aps.service.po.ServiceResult;
import com.iplant.aps.service.po.aps.APSBomBPM;
import com.iplant.aps.service.po.aps.APSBomBPMItem;
import com.iplant.aps.service.po.bms.BMSEmployee;
import com.iplant.aps.service.po.bpm.BPMTaskBase;
import com.iplant.aps.service.po.excel.ExcelData;
import com.iplant.aps.service.utils.StringUtils;
import com.iplant.aps.utils.RetCode;
import com.iplant.aps.utils.aps.ExcelReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 台车BOM审批(流程引擎版)
 *
 * @author PengYouWang
 *         2021-11-15 13:53:47
 */
@RestController
@RequestMapping("/api/APSBomBPM")
public class APSBomBPMController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(APSBomBPMController.class);

    final APSService wAPSService;

    final MyHelperService wMyHelperService;

    public APSBomBPMController(APSService wAPSService, MyHelperService wMyHelperService) {
        this.wAPSService = wAPSService;
        this.wMyHelperService = wMyHelperService;
    }

    /**
     * 查历史记录
     */
    @GetMapping("/History")
    public Object History(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            String wCode = StringUtils.parseString(request.getParameter("Code"));
            int wUpFlowID = StringUtils.parseInt(request.getParameter("UpFlowID"));
            int wOrderID = StringUtils.parseInt(request.getParameter("OrderID"));
            int wLineID = StringUtils.parseInt(request.getParameter("wLineID"));
            int wProductID = StringUtils.parseInt(request.getParameter("wProductID"));
            int wCustomerID = StringUtils.parseInt(request.getParameter("wCustomerID"));
            int wType = StringUtils.parseInt(request.getParameter("wType"));
            Calendar wStartTime = StringUtils.parseCalendar(request.getParameter("StartTime"));
            Calendar wEndTime = StringUtils.parseCalendar(request.getParameter("EndTime"));

            ServiceResult<List<APSBomBPM>> wServiceResult = wAPSService.APS_QueryBomBPMHistory(wLoginUser, wUpFlowID,
                    wCode, wUpFlowID, wOrderID, wLineID, wProductID, wCustomerID, wType, wStartTime, wEndTime);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 人员获取任务
     */
    @GetMapping("/EmployeeAll")
    public Object EmployeeAll(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            int wTagTypes = StringUtils.parseInt(request.getParameter("TagTypes"));
            Calendar wStartTime = StringUtils.parseCalendar(request.getParameter("StartTime"));
            Calendar wEndTime = StringUtils.parseCalendar(request.getParameter("EndTime"));

            ServiceResult<List<BPMTaskBase>> wServiceResult = wAPSService.APS_QueryBomBPMEmployeeAll(wLoginUser,
                    wTagTypes, wStartTime, wEndTime);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 人员获取任务
     */
    @GetMapping("/EmployeeAllWeb")
    public Object EmployeeAllWeb(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            String wCode = StringUtils.parseString(request.getParameter("Code"));
            int wUpFlowID = StringUtils.parseInt(request.getParameter("UpFlowID"));
            int wOrderID = StringUtils.parseInt(request.getParameter("OrderID"));
            int wLineID = StringUtils.parseInt(request.getParameter("wLineID"));
            int wProductID = StringUtils.parseInt(request.getParameter("wProductID"));
            int wCustomerID = StringUtils.parseInt(request.getParameter("wCustomerID"));
            int wType = StringUtils.parseInt(request.getParameter("wType"));

            int wStatus = StringUtils.parseInt(request.getParameter("Status"));
            Calendar wStartTime = StringUtils.parseCalendar(request.getParameter("StartTime"));
            Calendar wEndTime = StringUtils.parseCalendar(request.getParameter("EndTime"));

            String wMaterialName = StringUtils.parseString(request.getParameter("MaterialName"));
            String wMaterialNo = StringUtils.parseString(request.getParameter("MaterialNo"));

            ServiceResult<List<APSBomBPM>> wServiceResult = wAPSService.APS_QueryBomBPMEmployeeAllWeb(wLoginUser, wCode,
                    wUpFlowID, wOrderID, wLineID, wProductID, wCustomerID, wType, wStatus, wStartTime, wEndTime,
                    wMaterialName, wMaterialNo);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 查单条
     */
    @GetMapping("/Info")
    public Object Info(HttpServletRequest request) {
        Map<String, Object> wResult = new HashMap<>();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            int wID = StringUtils.parseInt(request.getParameter("ID"));

            ServiceResult<APSBomBPM> wServiceResult = wAPSService.APS_GetBomBPM(wLoginUser, wID);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
                this.SetResult(wResult, "Notice", wServiceResult.CustomResult.get("Notice"));
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 根据工位找班组长
     */
    @GetMapping("/UserByParts")
    public Object UserByParts(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            String wPartIDs = StringUtils.parseString(request.getParameter("PartIDs"));

            ServiceResult<List<BMSEmployee>> wServiceResult = wAPSService.APS_QueryUserByParts(wLoginUser, wPartIDs);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 重新创建配送单
     */
    @GetMapping("/ReCreatePSD")
    public Object ReCreatePSD(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            int wAPSBomAuditID = StringUtils.parseInt(request.getParameter("APSBomAuditID"));

            if (wAPSBomAuditID <= 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<Integer> wServiceResult = wAPSService.APS_ReCreatePSD_BOMAudit(wLoginUser,
                    wAPSBomAuditID);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 导入明细
     */
    @PostMapping("/ImportItem")
    public Object ImportOrder(HttpServletRequest request, @RequestParam("file") MultipartFile[] files) {
        Object wResult = new Object();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            if (files.length == 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, "提示：没有要上传的Excel文件！");
            }

            ServiceResult<List<APSBomBPMItem>> wServiceResult = new ServiceResult<>();
            ServiceResult<ExcelData> wExcelData = null;
            String wOriginalFileName = null;
            for (MultipartFile wMultipartFile : files) {
                wOriginalFileName = wMultipartFile.getOriginalFilename();

                assert wOriginalFileName != null;
                if (wOriginalFileName.contains("xlsx"))
                    wExcelData = ExcelReader.getInstance().readMultiSheetExcel(wMultipartFile.getInputStream(),
                            wOriginalFileName, "xlsx", 1000000);
                else if (wOriginalFileName.contains("xls"))
                    wExcelData = ExcelReader.getInstance().readMultiSheetExcel(wMultipartFile.getInputStream(),
                            wOriginalFileName, "xls", 1000000);

                assert wExcelData != null;
                if (StringUtils.isNotEmpty(wExcelData.FaultCode)) {
                    wResult = GetResult(RetCode.SERVER_CODE_ERR, wExcelData.FaultCode);
                    return wResult;
                }

                wServiceResult = wMyHelperService.APS_ImportItem(wLoginUser, wExcelData.Result);

                if (!StringUtils.isEmpty(wServiceResult.FaultCode))
                    break;
            }

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "导入成功!", wServiceResult.Result, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 校验时间范围
     */
    private String validateTimeRange(Calendar startTime, Calendar endTime) {
        try {
            Calendar baseTime = Calendar.getInstance();
            baseTime.set(2010, 0, 1, 0, 0, 0);

            if (startTime.before(baseTime)) {
                return "开始时间必须大于2010-01-01";
            }
            if (endTime.before(baseTime)) {
                return "结束时间必须大于2010-01-01";
            }
            if (startTime.compareTo(endTime) >= 0) {
                return "开始时间必须小于结束时间";
            }
        } catch (Exception ex) {
            logger.error("validateTimeRange", ex);
        }
        return null;
    }

    /**
     * 条件查询BOM明细
     */
    @GetMapping("/QueryBomItemList")
    public Object QueryBomItemList(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            if (CheckCookieEmpty(request)) {
                wResult = GetResult(RetCode.SERVER_CODE_UNLOGIN, "");
                return wResult;
            }

            BMSEmployee wLoginUser = GetSession(request);

            // 台车BOM评审单号
            String wCode = StringUtils.parseString(request.getParameter("Code"));
            // 车型ProductID
            int wProductID = StringUtils.parseInt(request.getParameter("ProductID"));
            // 修程LineID
            int wLineID = StringUtils.parseInt(request.getParameter("LineID"));
            // 局段CustomerID
            int wCustomerID = StringUtils.parseInt(request.getParameter("CustomerID"));
            // 订单OrderID
            int wOrderID = StringUtils.parseInt(request.getParameter("OrderID"));
            // WBS号
            String wWBSNo = StringUtils.parseString(request.getParameter("WBSNo"));
            // 工位PartID
            int wPartID = StringUtils.parseInt(request.getParameter("PartID"));
            // 工序PartPointID
            int wPartPointID = StringUtils.parseInt(request.getParameter("PartPointID"));
            // 物料名称
            String wMaterialName = StringUtils.parseString(request.getParameter("MaterialName"));
            // 物料编码
            String wMaterialNo = StringUtils.parseString(request.getParameter("MaterialNo"));
            // 单据状态（-1：全部，0：未完成，1：已完成）
            int wStatus = StringUtils.parseInt(request.getParameter("Status"));
            // SAP推送状态
            int wSAPStatus = StringUtils.parseInt(request.getParameter("SAPStatus"));
            // 必换偶换ReplaceType
            int wReplaceType = StringUtils.parseInt(request.getParameter("ReplaceType"));
            // 必修偶修OutSourceType
            int wOutSourceType = StringUtils.parseInt(request.getParameter("OutSourceType"));
            // 操作类型
            int wOperationType = StringUtils.parseInt(request.getParameter("OperationType"));
            // 开始时间
            Calendar wStartTime = StringUtils.parseCalendar(request.getParameter("StartTime"));
            // 结束时间
            Calendar wEndTime = StringUtils.parseCalendar(request.getParameter("EndTime"));

            // 时间校验
            String timeError = validateTimeRange(wStartTime, wEndTime);
            if (timeError != null) {
                return GetResult(RetCode.SERVER_CODE_ERR, timeError);
            }

            ServiceResult<List<APSBomBPMItem>> wServiceResult = wMyHelperService.APS_QueryBomItemList(wLoginUser,
                    wCode, wProductID, wLineID, wCustomerID, wOrderID, wWBSNo, wPartID, wPartPointID, wMaterialName,
                    wMaterialNo, wStatus, wSAPStatus, wReplaceType, wOutSourceType, wOperationType, wStartTime,
                    wEndTime);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }
}
